#include "./tcprelay/webRelay.h"

#include <map>
#include <vector>
#include <memory>
#include <string>
#include <sys/socket.h>
#include <lua.hpp>
using namespace yhaida;
using std::string;

std::map<string, InetAddress> redirections;

int main(int argc, char *argv[])
{
    lua_State *lua = luaL_newstate();
    if (luaL_dofile(lua, "../config.lua"))
    {
        abort();
    }
    lua_getglobal(lua, "server_request");
    lua_getglobal(lua, "server_addr");
    lua_getglobal(lua, "server_port");

    lua_getglobal(lua, "serverFastCGI_request");
    lua_getglobal(lua, "serverFastCGI_addr");
    lua_getglobal(lua, "serverFastCGI_port");

    lua_getglobal(lua, "tcprelay_port");
    lua_getglobal(lua, "tcprelay_numberThread");
    lua_getglobal(lua, "tcprelay_time");
    lua_getglobal(lua, "tcprelay_numberTunnel");

    std::string server_request = lua_tostring(lua, -10);
    std::string server_addr = lua_tostring(lua, -9);
    int server_port = lua_tonumber(lua, -8);
    std::string serverFastCGI_request = lua_tostring(lua, -7);
    std::string serverFastCGI_addr = lua_tostring(lua, -6);
    int serverFastCGI_port = lua_tonumber(lua, -5);
    int tcprelay_port = lua_tonumber(lua, -4);
    int tcprelay_numberThread = lua_tonumber(lua, -3);
    int tcprelay_time = lua_tonumber(lua, -2);
    int tcprelay_numberTunnel = lua_tonumber(lua, -1);

    lua_pop(lua, 10);

    // Logging::setLogLevel(Logging::TRACE);
    redirections[server_request] = InetAddress(server_addr, server_port);
    redirections[serverFastCGI_request] = InetAddress(serverFastCGI_addr, serverFastCGI_port);
    EventLoop loop;
    InetAddress listenAddr(tcprelay_port);
    WebRelay webrelay(&loop, listenAddr, redirections, tcprelay_time, tcprelay_numberTunnel);
    if (tcprelay_numberThread > 1)
    {
        webrelay.setThreadNum(tcprelay_numberThread);
    }
    webrelay.start();
    loop.loop();
}